//app.js
const api = require('api.js')
var o = require("utils/jquery.js");
App({
  onLaunch: function() {
    console.log('app onlaunch')
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })


  },

  onShow:function(){
    console.log('app onshow')
    // this.getcompany()

  },

  getcompany(){
    console.log(wx.getStorageSync("user_info"))
    if (wx.getStorageSync("user_info") != '') {
      var data = wx.getStorageSync("user_info")
      if (data.company_id == 0) {
        wx.reLaunch({
          url: '/pages/fillcompany/fillcompany',
        })
      }
    }
  },


  globalData: {
    userInfo: null,
    rdsession: '',
    acct_id: 1,
    openid: "",
    localSocket: {},
  },


  getauth: function(object) {
    console.log('getauth')
    wx.navigateTo({
      url: '/pages/usersq/usersq',
    })
  },
  request: function(object) {
    // console.log(object)
    var rdsession = wx.getStorageSync("rdsession");
    var openid = wx.getStorageSync("openid");
    var unionid = wx.getStorageSync("unionid");
    if (!object.data) {
      object.data = {};
    }
    wx.request({
      url: object.url,
      header: object.header || {
        'content-type': 'application/x-www-form-urlencoded',
        'rdsession': rdsession,
        'openid': openid,
        'unionid': unionid,
        'acctid': this.globalData.acct_id,
        'version': "2.0"
      },
      data: object.data || {},
      method: object.method || "GET",
      dataType: object.dataType || "json",
      success: function(res) {
        // console.log(res)
        if (res.data.errcode == 1003) {
          wx.navigateTo({
            url: '/pages/usersq/usersq',
          })
          return false;
        } else if (res.data.errcode == 1006){
          // console.log('需要绑定手机号')
          wx.navigateTo({
            url: '/pages/userss/userss',
          })
          return false;
        } else {
          if (object.success)
            object.success(res.data);
        }
      },
      fail: function(res) {
        var app = getApp();
        if (app.is_on_launch) {
          app.is_on_launch = false;
          wx.showModal({
            title: "网络请求出错",
            content: res.errMsg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                if (object.fail)
                  object.fail(res);
              }
            }
          });
        } else {
          wx.showToast({
            title: res.errMsg,
            image: "/images/icon-warning.png",
          });
          if (object.fail)
            object.fail(res);
        }
      },
      complete: function(res) {
        if (object.complete)
          object.complete(res);
      }
    });
  },
  upload: function(t) {
    var e = this;
    wx.chooseImage({
      success: function(n) {
        wx.showLoading({
          title: '正在上传...',
        });
        var i = n.tempFilePaths;
        wx.uploadFile({
          url: api.default.upload_img,
          filePath: i[0],
          name: "image",
          success: function(n) {
            wx.hideLoading();
            var o = JSON.parse(n.data);
            if (0 != o.errcode){
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              });
            } 
            else if ("function" == typeof t) {
              var i = o.data;
              t(i);
            }
          }
        });
      }
    });
  },
  str2Obj: function(t) {
    if ("string" != typeof t) return t;
    if (t.indexOf("&") < 0 && t.indexOf("=") < 0) return {};
    var e = t.split("&"),
      n = {};
    return o.each(e, function(t, e) {
      if (e.indexOf("=") > -1) {
        var o = e.split("=");
        n[o[0]] = o[1];
      }
    }), n;
  },
   /**
   * 上传文件
   */
  upload: function(t) {
    var e = this;
    wx.chooseImage({
      success: function(n) {
        wx.showLoading({
          title: '正在上传...',
        });
        var i = n.tempFilePaths;
        wx.uploadFile({
          url: api.default.upload_img,
          filePath: i[0],
          name: "image",
          success: function(n) {
            wx.hideLoading();
            var o = JSON.parse(n.data);
            if (0 != o.errcode){
              wx.showToast({
                title: '上传失败',
                icon: 'none'
              });
            } 
            else if ("function" == typeof t) {
              var i = o.data;
              t(i);
            }
          }
        });
      }
    });
  },
  
  /**
    * 订阅
    */
   follow: function (e) {
     var that = this
     if (wx.requestSubscribeMessage) {
       // var id = 'kNZaDlZVMGZEnt41Ni--znCt5srSXD7T4aPGtnkvvgg';
       this.request({
         url: api.default.config,
         method: 'POST',
         data: {
           name: e,
         },
         success: function (res) {
           if (res.errcode == 0 && res.data.value) {
             wx.requestSubscribeMessage({
               tmplIds: [res.data.value],
               success: function (es) {
                 for (let v in es) {
                   if (es[v] == 'accept') {
                     that.request({
                       url: api.default.addsubcount,
                       method: 'POST',
                       data: {
                         template: v,
                       }
                     })
                     wx.showToast({
                       title: '订阅成功',
                     })
                   }
                 }
               },
               fail: function (res) {
                 wx.showToast({
                   title: '订阅失败',
                   icon: 'none'
                 })
               }
             })
           }
         },
       });

     } else {

       wx.showModal({
         title: '提示',
         content: '当前微信版本过低，无法订阅功能，请升级到最新微信版本后重试。'
       })
     }
   },
   formatImg: function (html) {
    var newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {

      let processed = null;

      //如果原img标签不存在style属性值
      if (!match.match(/style=\"(.*)\"/gi)) {
        processed = match.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"');
      } else {
        processed = match.replace(/style=\"(.*)\"/gi, 'style="width:100%;height:auto;display:block"');
      }

      return processed;
    });
    return newContent;
  },


})